package com.bw.skill;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;

import java.lang.ref.WeakReference;

import retrofit2.http.PUT;

/**
 * @author KK
 * @description:
 * @date :2021/10/28 9:32
 */
public class TimeService extends Service {

    private long time;
    private TimeThread timeThread;
    private TimeHandler handler;

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public class TimeBinder extends Binder{
        public TimeService getTimeService(){
            return TimeService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        time = intent.getLongExtra("time",0);
        handler = new TimeHandler(this);
        timeThread = new TimeThread(handler);
        timeThread.start();
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        timeThread.interrupt();
        super.onDestroy();
    }

    public class TimeHandler extends Handler{
       private WeakReference<TimeService> weakReference;
       public TimeHandler(TimeService timeService){
           weakReference = new WeakReference<>(timeService);
       }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                if(weakReference == null){
                    return;
                }
                if(weakReference.get()==null){
                    return;
                }
                weakReference.get().time+=1;
            }

        }
    }
}
